//
//  YHFullscreenManager.swift
//  FuweiCloud
//
//  Created by michael on 2024/5/27.
//

import UIKit
import CoreMotion

public class YHMotionManager: NSObject {
  public static let notification = Notification.Name("MotionManagerNotification")
  private var motion: CMMotionManager?
  private let sensitive = 0.77
  public static let shared = {
    let mgr = YHMotionManager()
    mgr.motion = CMMotionManager()
    mgr.motion?.deviceMotionUpdateInterval = 1 / 40.0
    return mgr
  }()

  public func startMonitor(_ isStart: Bool) {
    guard motion?.isDeviceMotionAvailable == true else { return }
    if isStart {
      motion?.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: { [unowned self] device, _ in
        guard let x = device?.gravity.x, let y = device?.gravity.y else { return }
        var orientation: UIInterfaceOrientation?
        if fabs(x) > sensitive {
          orientation = x < 0 ?.landscapeLeft:.landscapeRight
        } else if fabs(y) > sensitive {
          orientation = y < 0 ?.portrait:.portraitUpsideDown
        }
        if let orientation {
          NotificationCenter.default.post(name: Self.notification, object: orientation)
        }
      })
    } else {
      motion?.stopDeviceMotionUpdates()
    }
  }
}

public class YHFullscreenManager: NSObject {
  public static let shared = YHFullscreenManager()

  public static func rotate(_ isLandscape: Bool, vc: UIViewController? = nil) {
    if #available(iOS 16.0, *) {
      vc?.setNeedsUpdateOfSupportedInterfaceOrientations()
      (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.requestGeometryUpdate(.iOS(interfaceOrientations: isLandscape ?.landscapeRight:.portrait))
    } else {
      UIViewController.attemptRotationToDeviceOrientation()
      UIDevice.current.setValue(isLandscape ?UIInterfaceOrientation.landscapeRight.rawValue:UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
    }
    YHApplication.statusBarOrientation = YHIsLandscape ?.landscapeRight:.portrait
  }

  public static func switching(_ vc: UIViewController? = nil) {
    rotate(!YHIsLandscape, vc: vc)
  }
}
